/**
 * 自定义Vue指令
 * @author cheval
 */
import {Message} from "element-ui";
import router from "@/router";

const directive = {
    install(Vue,options) {
        // 自定义权限指令
        Vue.directive('hasPermission', {
            inserted(el,binding,vnode) {
                const {value} = binding
                const hadPermission = JSON.parse(sessionStorage.getItem('userinfo')).permissions
                if (hadPermission === null || hadPermission === undefined) {
                    sessionStorage.removeItem('userinfo')
                    sessionStorage.removeItem('token')
                    router.replace('/')
                    Message.warning("请重新登录")
                    return
                }
                const adminPermission = '*:*:*'
                if (value === undefined || value === null || !(value instanceof Array)) {
                    throw new Error("please set permission sign,example ['*:*:*']")
                }
                if (value && value instanceof Array && value.length > 0) {
                    // some 方法对数组进行进行遍历，只要有一个返回true,那么some方法结果就时true,常用于判断一个数组中是否包含另一个数组的某一个元素
                    let flag = hadPermission.some(item => {
                        return adminPermission === item || value.includes(item)
                    })
                    if (!flag) {
                        el.parentNode && el.parentNode.removeChild(el)
                    }
                }
            }
        })
    }
}

export default directive